<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="id?'编辑月卡':'添加月卡'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form ref="form" label-width="100px" :model="cardData" :rules="rules">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="cardData.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="cardData.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="cardData.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="cardData.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="dateForm" label-width="100px" :model="cardData" :rules="dateRules">
            <el-form-item label="有效日期" prop="cardStartDate">
              <el-date-picker
                v-model="cardData.cardStartDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="cardData.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="cardData.paymentMethod" placeholder="请选择">
                <el-option
                  v-for="item in cardData.payment"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="submit">{{ id?'编辑':'添加' }}</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addCardAPI, getEditCardAPI, editCardAPI } from '@/api/addCard'
export default {
  data() {
    return {

      // 表单数据
      cardData: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: '',
        cardStartDate: '',
        cardEndDate: '',
        paymentAmount: '',
        paymentMethod: null,
        carInfoId: null,
        rechargeId: null,
        // 支付方式
        payment: [

          {
            industryCode: 'Alipay',
            industryName: '支付宝'
          },
          {
            industryCode: 'WeChat',
            industryName: '微信'
          },
          {
            industryCode: 'Cash',
            industryName: '现金'
          }
        ]

      },
      // 检验规则,检验姓名号码等
      rules: {
        personName: [
          { required: true, message: '请输入车主姓名', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            const reg = /^1[3456789]\d{9}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error('请输入正确的联系方式'))
            }
          }
          }
        ],
        carNumber: [
          { required: true, message: '请输入车辆号码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            const reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]$/
            if (!reg.test(value)) {
              callback(new Error('请输入正确的车辆品牌'))
            } else {
              callback()
            }
          } }
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }

        ]

      },
      // 日期校验规则
      dateRules: {
        cardStartDate: [{ required: true, message: '请选择有效日期', trigger: 'blur' }],
        paymentAmount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }]
      }
    }
  },
  // 计算属性，将ID存入到计算属性中
  computed: {
    // 获取路由参数的id
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    // 有id则执行渲染
    if (this.id) {
      this.getEditCard(this.id)
    }
  },
  methods: {
    // 添加月卡
    async addCard() {
      // 获取表单数据
      const { personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod } = this.cardData

      const res = await addCardAPI({
        personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod,
        cardStartDate: this.cardData.cardStartDate[0],
        cardEndDate: this.cardData.cardStartDate[1]
      })
      console.log(res)
    },
    // 添加月卡
    submit() {
      // 检验表单，是否完善，并提交
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$refs.dateForm.validate(async(dateValid) => {
            if (dateValid) {
              // 添加完成后清空表单，并后退到上一页
              // 有id就是编辑，没有就是添加
              if (this.id) {
                await this.editCard()
                this.$message.success('编辑成功')
              } else {
                await this.addCard()
                this.$message.success('添加成功')
              }
              this.$refs.form.resetFields()
              this.$refs.dateForm.resetFields()
              this.$router.back()
            } else {
              this.$message.error('请完善信息')
            }
          })
        } else {
          this.$message.error('请完善信息')
        }
      })
    },
    // 重置按钮
    reset() {
      this.$refs.form.resetFields()
      this.$refs.dateForm.resetFields()
    },
    // 获取编辑详情
    async getEditCard(id) {
      const res = await getEditCardAPI(id)
      this.cardData = {
        ... res.data,
        // 防止没有下拉框，使用展开运算符
        payment: [...this.cardData.payment],
        cardStartDate: [res.data.cardStartDate, res.data.cardEndDate]

      }
      this.cardData.carInfoId = res.data.carInfoId
      this.cardData.rechargeId = res.data.rechargeId
    },
    // 编辑月卡并提交
    async editCard() {
      const { personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod, carInfoId, rechargeId } = this.cardData
      await editCardAPI({ personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod, cardStartDate: this.cardData.cardStartDate[0], cardEndDate: this.cardData.cardStartDate[1], carInfoId, rechargeId })
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview{
      img{
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
